import json
from pathlib import Path

import qrcode
from PIL import Image, ImageDraw, ImageFont


# 生成背景图片（650 * 1000）
def create_background():
    bg = Image.new("RGB", (2480, 3508), (60, 172, 127))
    white = Image.new("RGB", (2480, 224), "white")
    bg.paste(white, (0, 945))
    bg.paste(white, (0, 945 + 1169))
    bg.paste(white, (0, 945 + 1169 + 1169))
    black = Image.new("RGB", (2, 3508), "black")
    bg.paste(black, (825, 0))
    bg.paste(black, (825 + 826, 0))
    return bg


def create_qr(url):
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=15,
        border=2,
    )
    qr.add_data(url)
    qr.make(fit=True)

    img = qr.make_image(fill_color="black", back_color="white")
    return img


def add_text_(draw, text, start_height, text_height, font_size, color):
    font = ImageFont.truetype('../微软雅黑.ttc', font_size)
    text_size = draw.textsize(text, font=font)
    coordinates = (
        (826 - text_size[0]) // 2,
        start_height - (text_size[1] - text_height) // 2
    )
    draw.text(coordinates, text, fill=color, font=font)


def add_text(room, organization, bg, qr, name_size, org_size):
    coordinates = ((826 - qr.size[0]) // 2, 226)
    bg.paste(qr, coordinates)

    draw = ImageDraw.Draw(bg)

    add_text_(draw, f'房号：{room}', 0, 226, name_size, 'white')
    add_text_(draw, '扫码注册，开启智慧生活', 721, 224, 60, 'white')
    add_text_(draw, organization, 945, 224, org_size, 'black')


def create_img(room, organization, name_size, org_size):
    # 创建背景图片
    bg_size = (827, 1169)
    green = (60, 172, 127)
    bg = Image.new("RGB", bg_size, green)
    white_size = (827, 224)
    white = Image.new("RGB", white_size, "white")
    bg.paste(white, (0, 945))

    qr = create_qr(room["url"].replace("nezha", "www"))

    add_text(room["name"], organization, bg, qr, name_size, org_size)
    p = Path("qrcode")
    p.exists() or p.mkdir(parents=True)
    bg.save(p / f"{room['name']}.png", dpi=(300.0, 300.0))


if __name__ == '__main__':
    with open("source.json", encoding="utf-8")as f:
        data = json.load(f)

    for i in data:
        create_img(i, "深圳市智慧社区科技有限公司", 60, 55)
        # break
